package com.lyun.interceptor;

import com.lyun.common.BaseContext;
import com.lyun.common.JwtUtils;
import com.lyun.common.LoginExpiredException;
import com.lyun.common.MyBusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * app的拦截器 每次会在控制台输出一下具体的请求路径 并且每次请求时 会在线程中写入id
 */
public class BaseServiceInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        System.out.println(request.getRequestURI());

        String token = request.getHeader("Authorization");
        System.out.println("BaseServiceInterceptor...token = " + token);

        try {
            Claims claims = JwtUtils.getClaims(token);
            Object id = claims.get("id");
            if (id == null) {
                return false;
            }
            System.out.println("BaseServiceInterceptor...id = " + id);
            BaseContext.setCurrentId(((Integer) id).longValue());
        } catch (ExpiredJwtException e) {
            throw new LoginExpiredException("登录过期");
        }

        return true;
    }
}